package com.mrx.commons.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * @author Mr.X
 * @since 2023-05-10 09:17
 */
@Component
public class DelayTask {

    private static final BlockingDeque<Runnable> taskQueue = new LinkedBlockingDeque<>();

    private static final Logger logger = LoggerFactory.getLogger(DelayTask.class);

    @Async
    @Scheduled(cron = "0/10 * * * * ?")
    public void execute() {
        Runnable task = taskQueue.pollFirst();
        if (task != null) {
            logger.info("准备执行延迟队列中的第一个任务: {}, 队列中还有 {} 个任务待执行", task, taskQueue.size());
            task.run();
        }
    }

    /**
     * 向延迟队列的末尾插入一条任务
     *
     * @param r 要执行的任务
     */
    public void offerTask(Runnable r) {
        taskQueue.offerLast(r);
    }

}
